<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 生产计划管理 - 核心生产计划工具
 *
 * @icon fa fa-calendar
 * @remark 主要生产计划模块，负责生产任务的详细安排、资源分配和进度跟踪
 */
class ProductionPlan extends Backend
{
    /**
     * ProductionPlan模型对象
     * @var \app\admin\model\scanwork\ProductionPlan
     */
    protected $model = null;

    /**
     * 无需登录的方法
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需权限的方法
     * @var array
     */
    protected $noNeedRight = ['getOrderDetails', 'getProductDetails', 'getProcessDetails', 'getEmployeeDetails'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\ProductionPlan;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['order', 'product', 'model', 'customer'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            // 添加统计信息
            $rows = [];
            foreach ($list as $item) {
                $row = $item->toArray();
                $stats = $item->getPlanStats();
                $row['completion_rate'] = $stats['completion_rate'];
                $row['remaining_quantity'] = $stats['remaining_quantity'];
                $row['allocation_count'] = $stats['allocation_count'];
                $row['actual_quantity'] = $stats['total_reported']; // 将total_reported映射为actual_quantity
                $rows[] = $row;
            }

            $result = array("total" => $list->total(), "rows" => $rows);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        // 获取订单列表（显示订单名称）
        $orders = \app\admin\model\scanwork\Order::where('status', '<>', 2)->select();
        $orderList = [];
        foreach ($orders as $order) {
            $orderList[$order->id] = $order->order_name ?: $order->order_no;
        }
        $this->view->assign('orderList', $orderList);
        
        // 获取产品列表
        $productList = \app\admin\model\scanwork\Product::where('status', 1)
            ->column('name', 'id');
        $this->view->assign('productList', $productList);
        
        // 获取客户列表
        $customerList = \app\admin\model\scanwork\Customer::where('status', 1)
            ->column('customer_name', 'id');
        $this->view->assign('customerList', $customerList);

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 生成计划编码
                if (empty($params['plan_code'])) {
                    $params['plan_code'] = $this->generatePlanCode();
                }
                
                // 生成计划名称
                if (empty($params['plan_name'])) {
                    $params['plan_name'] = $params['product_name'] . ' - ' . $params['product_model'] . ' - 生产计划';
                }
                
                // 检查计划编码是否唯一
                if (!$this->model->checkCodeUnique($params['plan_code'])) {
                    $this->error('计划编码已存在');
                }
                
                // 处理时间字段
                if (!empty($params['planned_start_time'])) {
                    $params['planned_start_time'] = strtotime($params['planned_start_time']);
                }
                if (!empty($params['planned_end_time'])) {
                    $params['planned_end_time'] = strtotime($params['planned_end_time']);
                }
                
                // 处理状态字段，确保是整数
                if (isset($params['status'])) {
                    $params['status'] = (int)$params['status'];
                }
                
                // 字段映射：planned_quantity -> total_quantity
                if (isset($params['planned_quantity'])) {
                    $params['total_quantity'] = (int)$params['planned_quantity'];
                    unset($params['planned_quantity']);
                }
                
                // 根据产品名称和型号名称获取对应的ID
                if (!empty($params['product_name']) && !empty($params['product_model'])) {
                    // 获取产品ID
                    $product = \app\admin\model\scanwork\Product::where('name', $params['product_name'])->find();
                    if ($product) {
                        $params['product_id'] = $product->id;
                    }
                    
                    // 获取型号ID
                    $model = \app\admin\model\scanwork\ProductModel::where('name', $params['product_model'])->find();
                    if ($model) {
                        $params['model_id'] = $model->id;
                    }
                }
                
                // 根据订单ID获取客户ID
                if (!empty($params['order_id'])) {
                    $order = \app\admin\model\scanwork\Order::find($params['order_id']);
                    if ($order && !empty($order->customer_name)) {
                        $customer = \app\admin\model\scanwork\Customer::where('customer_name', $order->customer_name)->find();
                        if ($customer) {
                            $params['customer_id'] = $customer->id;
                        }
                    }
                }

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    
                    $result = $this->model->allowField(true)->save($params);
                    
                    // 如果保存成功，生成默认工序顺序和关键节点
                    if ($result !== false) {
                        $this->model->save([
                            'process_sequence' => $this->model->generateDefaultProcessSequence(),
                            'key_milestones' => $this->model->generateKeyMilestones()
                        ]);
                    }
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        
        // 获取订单列表（显示订单名称）
        $orders = \app\admin\model\scanwork\Order::where('status', '<>', 2)->select();
        $orderList = [];
        foreach ($orders as $order) {
            $orderList[$order->id] = $order->order_name ?: $order->order_no;
        }
        $this->view->assign('orderList', $orderList);
        
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 处理时间字段
                if (!empty($params['planned_start_time'])) {
                    $params['planned_start_time'] = strtotime($params['planned_start_time']);
                }
                if (!empty($params['planned_end_time'])) {
                    $params['planned_end_time'] = strtotime($params['planned_end_time']);
                }
                if (!empty($params['actual_start_time'])) {
                    $params['actual_start_time'] = strtotime($params['actual_start_time']);
                }
                if (!empty($params['actual_end_time'])) {
                    $params['actual_end_time'] = strtotime($params['actual_end_time']);
                }
                
                // 处理状态字段，确保是整数
                if (isset($params['status'])) {
                    $params['status'] = (int)$params['status'];
                }
                
                // 字段映射：planned_quantity -> total_quantity
                if (isset($params['planned_quantity'])) {
                    $params['total_quantity'] = (int)$params['planned_quantity'];
                    unset($params['planned_quantity']);
                }
                
                $result = false;
                Db::startTrans();
                try {
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 查看生产计划关联的分工分配
     */
    public function allocations($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取关联的分工分配
        $allocations = \app\admin\model\scanwork\Allocation::with(['process', 'user'])
            ->where('plan_id', $row->id)
            ->select();
        
        // 调试信息
        \think\Log::info('分配记录数量：' . count($allocations));
        foreach ($allocations as $allocation) {
            \think\Log::info('分配ID：' . $allocation->id . '，用户ID：' . $allocation->user_id . '，用户信息：' . json_encode($allocation->user));
        }
        
        $this->view->assign('row', $row);
        $this->view->assign('allocations', $allocations);
        return $this->view->fetch();
    }

    /**
     * 工序分配管理
     */
    public function allocate($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取可用的工序
        $processList = \app\admin\model\scanwork\Process::where('status', 1)
            ->column('name', 'id');
        $this->view->assign('processList', $processList);
        
        // 获取可用的工人（从前端用户表获取）
        $userList = \app\common\model\User::where('status', 'normal')
            ->column('nickname', 'id');
        $this->view->assign('userList', $userList);
        
        // 获取每个工序的分配情况
        $processAllocations = \app\admin\model\scanwork\Allocation::where('plan_id', $row->id)
            ->field('process_id, SUM(quantity) as allocated_quantity')
            ->group('process_id')
            ->select();
        
        // 构建工序分配数据
        $processAllocationData = [];
        foreach ($processAllocations as $allocation) {
            $processAllocationData[$allocation->process_id] = $allocation->allocated_quantity;
        }
        
        // 为每个工序添加分配信息
        $processListWithAllocation = [];
        foreach ($processList as $processId => $processName) {
            $allocated = isset($processAllocationData[$processId]) ? $processAllocationData[$processId] : 0;
            $remaining = $row->total_quantity - $allocated;
            
            $processListWithAllocation[$processId] = [
                'id' => $processId,
                'name' => $processName,
                'total_quantity' => $row->total_quantity,
                'allocated_quantity' => $allocated,
                'remaining_quantity' => $remaining
            ];
        }
        
        $this->view->assign('processListWithAllocation', $processListWithAllocation);
        
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 批量分配工序
     */
    public function batchAllocate($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取可用的工序
        $processList = \app\admin\model\scanwork\Process::where('status', 1)
            ->column('name', 'id');
        $this->view->assign('processList', $processList);
        
        // 获取可用的工人（从前端用户表获取）
        $userList = \app\common\model\User::where('status', 'normal')
            ->column('nickname', 'id');
        $this->view->assign('userList', $userList);
        
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 保存批量分配
     */
    public function saveBatchAllocate()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            
            // 调试信息
            \think\Log::info('分配保存参数：' . json_encode($params));
            
            $planId = $params['plan_id'];
            $allocations = $params['allocations'];
            
            if (empty($planId) || empty($allocations)) {
                $this->error('参数不完整');
            }
            
            $plan = $this->model->get($planId);
            if (!$plan) {
                $this->error('生产计划不存在');
            }
            
            $successCount = 0;
            $errors = [];
            
            foreach ($allocations as $allocation) {
                if (empty($allocation['process_id']) || empty($allocation['user_id']) || empty($allocation['quantity'])) {
                    \think\Log::info('跳过无效分配：' . json_encode($allocation));
                    continue;
                }
                
                // 生成产品编号前缀
                $order = \app\admin\model\scanwork\Order::get($plan->order_id);
                $model = \app\admin\model\scanwork\ProductModel::get($plan->model_id);
                $process = \app\admin\model\scanwork\Process::get($allocation['process_id']);
                $itemPrefix = '';
                if ($order && $model && $process) {
                    $itemPrefix = $order->order_no . '-' . $model->name . '-' . $process->name . '-';
                }
                
                $data = [
                    'plan_id' => $planId,
                    'order_id' => $plan->order_id,
                    'model_id' => $plan->model_id,
                    'process_id' => $allocation['process_id'],
                    'user_id' => $allocation['user_id'],
                    'quantity' => $allocation['quantity'],
                    'work_type' => 'piece',
                    'type' => 'piece',
                    'status' => 0,
                    'item_prefix' => $itemPrefix,
                    'createtime' => time(),
                    'updatetime' => time()
                ];
                
                \think\Log::info('保存分配数据：' . json_encode($data));
                try {
                    $allocationModel = \app\admin\model\scanwork\Allocation::create($data);
                    \think\Log::info('分配保存成功，ID：' . $allocationModel->id);
                    
                    // 生成产品编号（仅计件工作）
                    if ($allocationModel && $allocationModel->id && $allocation['quantity'] > 0 && $itemPrefix) {
                        $itemNos = \app\admin\model\scanwork\ProductItem::generateItemNos($allocationModel->id, $itemPrefix, $allocation['quantity']);
                        $createResult = \app\admin\model\scanwork\ProductItem::createItems($allocationModel->id, $itemNos);
                        if (!$createResult) {
                            throw new Exception('产品编号生成失败');
                        }
                        \think\Log::info('产品编号生成成功，数量：' . count($itemNos));
                    }
                    
                    // 自动生成报工二维码
                    try {
                        $this->generateQrcodeForAllocation($allocationModel->id);
                        \think\Log::info('二维码生成成功，分配ID：' . $allocationModel->id);
                    } catch (\Exception $e) {
                        \think\Log::error('二维码生成失败：' . $e->getMessage());
                        // 二维码生成失败不影响分配保存
                    }
                    
                    $successCount++;
                } catch (\Exception $e) {
                    \think\Log::error('单条分配保存失败：' . $e->getMessage());
                    $errors[] = $e->getMessage();
                }
            }
            
            if ($successCount == 0) {
                $this->error('没有有效的分配数据');
            }
            
            if (!empty($errors)) {
                $this->error('部分分配保存失败：' . implode('; ', $errors));
            }
            
            $this->success('批量分配成功，共保存' . $successCount . '条记录');
        }
        $this->error('参数错误');
    }

    /**
     * 生产进度统计
     */
    public function progressStats($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取分工分配统计
        $allocations = \app\admin\model\scanwork\Allocation::with(['process', 'user'])
            ->where('order_id', $row->order_id)
            ->where('model_id', $row->model_id)
            ->select();
        
        $stats = [
            'total_allocated' => 0,
            'total_reported' => 0,
            'total_hours' => 0,
            'total_piece_wage' => 0,
            'total_hourly_wage' => 0,
            'total_wage' => 0,
            'process_stats' => [],
            'worker_stats' => []
        ];
        
        foreach ($allocations as $allocation) {
            $stats['total_allocated'] += $allocation->quantity;
            
            // 从报工记录表获取实际报工数据
            $reports = \app\admin\model\scanwork\Report::where('allocation_id', $allocation->id)
                ->where('status', 1) // 已审核的报工记录
                ->select();
            
            $allocationReported = 0;
            $allocationHours = 0;
            $allocationWage = 0;
            
            foreach ($reports as $report) {
                $allocationReported += $report->quantity;
                $allocationHours += $report->actual_hours;
                $allocationWage += $report->wage;
            }
            
            $stats['total_reported'] += $allocationReported;
            $stats['total_hours'] += $allocationHours;
            $stats['total_piece_wage'] += $allocationWage;
            
            // 按工序统计
            $processName = $allocation->process->name;
            if (!isset($stats['process_stats'][$processName])) {
                $stats['process_stats'][$processName] = [
                    'allocated' => 0,
                    'reported' => 0,
                    'hours' => 0,
                    'completion_rate' => 0
                ];
            }
            $stats['process_stats'][$processName]['allocated'] += $allocation->quantity;
            $stats['process_stats'][$processName]['reported'] += $allocationReported;
            $stats['process_stats'][$processName]['hours'] += $allocationHours;
            
            // 按工人统计
            $workerName = $allocation->user->nickname;
            if (!isset($stats['worker_stats'][$workerName])) {
                $stats['worker_stats'][$workerName] = [
                    'allocated' => 0,
                    'reported' => 0,
                    'hours' => 0,
                    'wage' => 0,
                    'hourly_wage' => 0,
                    'total_wage' => 0,
                    'completion_rate' => 0,
                    'efficiency' => 0
                ];
            }
            $stats['worker_stats'][$workerName]['allocated'] += $allocation->quantity;
            $stats['worker_stats'][$workerName]['reported'] += $allocationReported;
            $stats['worker_stats'][$workerName]['hours'] += $allocationHours;
            $stats['worker_stats'][$workerName]['wage'] += $allocationWage;
        }
        
        // 计算完成率、工时工资、总工资等
        foreach ($stats['process_stats'] as &$process) {
            if ($process['allocated'] > 0) {
                $process['completion_rate'] = round(($process['reported'] / $process['allocated']) * 100, 1);
            }
        }
        
        foreach ($stats['worker_stats'] as &$worker) {
            // 计算完成率
            if ($worker['allocated'] > 0) {
                $worker['completion_rate'] = round(($worker['reported'] / $worker['allocated']) * 100, 1);
            }
            
            // 计算工时工资（每小时15元）
            $worker['hourly_wage'] = round($worker['hours'] * 15, 2);
            
            // 计算总工资
            $worker['total_wage'] = round($worker['wage'] + $worker['hourly_wage'], 2);
            
            // 计算工作效率
            if ($worker['hours'] > 0) {
                $worker['efficiency'] = round($worker['reported'] / $worker['hours'], 2);
            }
        }
        
        // 计算总计
        $stats['total_hourly_wage'] = round($stats['total_hours'] * 15, 2);
        $stats['total_wage'] = round($stats['total_piece_wage'] + $stats['total_hourly_wage'], 2);
        
        $this->view->assign('row', $row);
        $this->view->assign('stats', $stats);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    // 检查是否有关联的分工分配
                    $allocationCount = \app\admin\model\scanwork\Allocation::where('order_id', $item->order_id)->count();
                    if ($allocationCount > 0) {
                        throw new Exception("生产计划【{$item->plan_name}】下还有{$allocationCount}个分工分配，请先删除相关分工");
                    }
                    
                    $count += $item->delete();
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        } else {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
    }

    /**
     * 查看详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取计划统计信息
        $stats = $row->getPlanStats();
        
        // 获取分工分配详情
        $allocations = \app\admin\model\scanwork\Allocation::with(['model.product', 'process', 'user'])
            ->where('order_id', $row->order_id)
            ->select();
        
        // 获取工序顺序
        $processSequence = $row->process_sequence;
        
        // 获取关键生产节点
        $keyMilestones = $row->key_milestones;
        
        $this->view->assign('row', $row);
        $this->view->assign('stats', $stats);
        $this->view->assign('allocations', $allocations);
        $this->view->assign('processSequence', $processSequence);
        $this->view->assign('keyMilestones', $keyMilestones);
        
        return $this->view->fetch();
    }

    /**
     * 生成计划编码
     */
    private function generatePlanCode()
    {
        $prefix = 'JH-' . date('Y') . '-';
        $lastCode = $this->model->where('plan_code', 'like', $prefix . '%')
            ->order('plan_code desc')
            ->value('plan_code');
        
        if ($lastCode) {
            $lastNumber = intval(substr($lastCode, -3));
            $newNumber = $lastNumber + 1;
        } else {
            $newNumber = 1;
        }
        
        return $prefix . str_pad($newNumber, 3, '0', STR_PAD_LEFT);
    }

    /**
     * 基于订单生成生产计划
     */
    public function generateFromOrder()
    {
        $orderId = $this->request->post('order_id');
        if (!$orderId) {
            $this->error('请选择订单');
        }
        
        $order = \app\admin\model\scanwork\Order::get($orderId);
        if (!$order) {
            $this->error('订单不存在');
        }
        
        // 检查是否已有生产计划
        $existingPlan = $this->model->where('order_id', $orderId)->find();
        if ($existingPlan) {
            $this->error('该订单已存在生产计划');
        }
        
        try {
            Db::startTrans();
            
            // 获取订单型号
            $orderModels = \app\admin\model\scanwork\OrderModel::with(['model.product'])
                ->where('order_id', $orderId)
                ->select();
            
            foreach ($orderModels as $orderModel) {
                $planData = [
                    'plan_code' => $this->generatePlanCode(),
                    'order_id' => $orderId,
                    'product_id' => $orderModel->model->product_id,
                    'model_id' => $orderModel->model_id,
                    'customer_id' => $order->customer_id,
                    'plan_name' => $order->order_no . ' - ' . $orderModel->model->product->name . ' - ' . $orderModel->model->name,
                    'product_name' => $orderModel->model->product->name,
                    'product_model' => $orderModel->model->name,
                    'total_quantity' => $orderModel->quantity,
                    'planned_start_time' => time(),
                    'planned_end_time' => $order->delivery_time ?: (time() + 7 * 86400), // 默认7天后
                    'status' => 0,
                    'createtime' => time()
                ];
                
                $plan = $this->model->create($planData);
                
                // 生成默认工序顺序和关键节点
                $plan->save([
                    'process_sequence' => $plan->generateDefaultProcessSequence(),
                    'key_milestones' => $plan->generateKeyMilestones()
                ]);
            }
            
            Db::commit();
            $this->success('生产计划生成成功');
            
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('生成失败：' . $e->getMessage());
        }
    }

    /**
     * 开始计划
     */
    public function start($ids = null)
    {
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $plan = $this->model->get($ids);
        if (!$plan) {
            $this->error('生产计划不存在');
        }
        
        try {
            $plan->start();
            $this->success('计划已开始');
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 暂停计划
     */
    public function pause($ids = null)
    {
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $plan = $this->model->get($ids);
        if (!$plan) {
            $this->error('生产计划不存在');
        }
        
        try {
            $plan->pause();
            $this->success('计划已暂停');
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 恢复计划
     */
    public function resume($ids = null)
    {
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $plan = $this->model->get($ids);
        if (!$plan) {
            $this->error('生产计划不存在');
        }
        
        try {
            $plan->resume();
            $this->success('计划已恢复');
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 完成计划
     */
    public function complete($ids = null)
    {
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $plan = $this->model->get($ids);
        if (!$plan) {
            $this->error('生产计划不存在');
        }
        
        try {
            $plan->complete();
            $this->success('计划已完成');
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 更新计划进度
     */
    public function updateProgress($ids = null)
    {
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $plan = $this->model->get($ids);
        if (!$plan) {
            $this->error('生产计划不存在');
        }
        
        try {
            $plan->updateProgress();
            $this->success('进度更新成功');
        } catch (\Exception $e) {
            $this->error('更新失败：' . $e->getMessage());
        }
    }

    /**
     * 获取计划统计信息
     */
    public function getPlanStats($ids = null)
    {
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $plan = $this->model->get($ids);
        if (!$plan) {
            $this->error('生产计划不存在');
        }
        
        $stats = $plan->getPlanStats();
        $this->success('', null, $stats);
    }

    /**
     * 编辑工序顺序
     */
    public function editProcessSequence($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取所有工序
        $allProcesses = \app\admin\model\scanwork\Process::where('status', 1)->select();
        $this->view->assign('allProcesses', $allProcesses);
        
        if ($this->request->isPost()) {
            $processSequence = $this->request->post('process_sequence', []);
            
            try {
                $row->save(['process_sequence' => $processSequence]);
                $this->success('工序顺序更新成功');
            } catch (\Exception $e) {
                $this->error('更新失败：' . $e->getMessage());
            }
        }
        
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 编辑关键生产节点
     */
    public function editKeyMilestones($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $keyMilestones = $this->request->post('key_milestones', []);
            
            try {
                $row->save(['key_milestones' => $keyMilestones]);
                $this->success('关键生产节点更新成功');
            } catch (\Exception $e) {
                $this->error('更新失败：' . $e->getMessage());
            }
        }
        
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 根据订单获取产品和型号信息
     */
    public function getOrderProducts()
    {
        $orderId = $this->request->get('order_id');
        if (!$orderId) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }

        try {
            $order = \app\admin\model\scanwork\Order::with(['orderModels.model.product'])->find($orderId);
            if (!$order) {
                return json(['code' => 0, 'msg' => '订单不存在']);
            }

            $products = [];
            foreach ($order->orderModels as $orderModel) {
                $model = $orderModel->model;
                $product = $model->product;
                
                $products[] = [
                    'product_id' => $product->id,
                    'product_name' => $product->name,
                    'model_id' => $model->id,
                    'model_name' => $model->name,
                    'quantity' => $orderModel->quantity
                ];
            }

            return json(['code' => 1, 'msg' => '获取成功', 'data' => $products]);

        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '获取订单产品信息失败：' . $e->getMessage()]);
        }
    }

    /**
     * 生产进度跟踪 - 多维度统计
     */
    public function progress()
    {
        try {
            // 获取筛选参数
            $orderId = $this->request->get('order_id', '');
            $planId = $this->request->get('plan_id', '');
            $processId = $this->request->get('process_id', '');
            $userId = $this->request->get('user_id', '');
            $dateRange = $this->request->get('date_range', '');
            
            // 构建查询条件
            $where = [];
            if ($orderId) {
                $where['order_id'] = $orderId;
            }
            if ($planId) {
                $where['id'] = $planId;
            }
            
            // 获取生产计划
            $plans = $this->model->where($where)->with(['order'])->select();
            
            // 1. 按订单维度统计
            $orderStats = [];
            $orderProgress = [];
            
            // 2. 按小工单维度统计
            $workOrderStats = [];
            
            // 3. 按工序维度统计
            $processStats = [];
            
            // 4. 按员工维度统计
            $employeeStats = [];
            
            // 5. 按产品维度统计
            $productStats = [];
            
            // 6. 整体统计
            $overallStats = [
                'total_orders' => 0,
                'total_plans' => 0,
                'total_allocations' => 0,
                'total_reports' => 0,
                'total_quantity' => 0,
                'completed_quantity' => 0,
                'overall_completion_rate' => 0
            ];
            
            $processedOrders = [];
            
            foreach ($plans as $plan) {
                $overallStats['total_plans']++;
                $overallStats['total_quantity'] += $plan->total_quantity;
                
                // 直接从报工表计算该计划的已完成数量
                $planCompletedQuantity = 0;
                $planAllocations = \app\admin\model\scanwork\Allocation::where('order_id', $plan->order_id)
                    ->where('model_id', $plan->model_id)
                    ->select();
                foreach ($planAllocations as $allocation) {
                    $reports = \app\admin\model\scanwork\Report::where('allocation_id', $allocation->id)
                        ->where('status', 1)
                        ->sum('quantity');
                    $planCompletedQuantity += $reports ?: 0;
                }
                $overallStats['completed_quantity'] += $planCompletedQuantity;
                
                // 按订单统计
                if ($plan->order) {
                    $orderId = $plan->order->id;
                    if (!isset($processedOrders[$orderId])) {
                        $processedOrders[$orderId] = true;
                        $overallStats['total_orders']++;
                        
                        $orderStats[$orderId] = [
                            'order_id' => $orderId,
                            'order_name' => $plan->order->order_name,
                            'order_no' => $plan->order->order_no,
                            'total_plans' => 0,
                            'total_quantity' => 0,
                            'completed_quantity' => 0,
                            'completion_rate' => 0,
                            'plans' => []
                        ];
                    }
                    
                    $orderStats[$orderId]['total_plans']++;
                    $orderStats[$orderId]['total_quantity'] += $plan->total_quantity;
                    $orderStats[$orderId]['completed_quantity'] += $planCompletedQuantity;
                    
                    $orderStats[$orderId]['plans'][] = [
                        'plan_id' => $plan->id,
                        'plan_code' => $plan->plan_code,
                        'plan_name' => $plan->plan_name,
                        'product_name' => $plan->product_name,
                        'product_model' => $plan->product_model,
                        'total_quantity' => $plan->total_quantity,
                        'actual_quantity' => $planCompletedQuantity,
                        'completion_rate' => $plan->total_quantity > 0 ? round(($planCompletedQuantity / $plan->total_quantity) * 100, 1) : 0,
                        'status' => $plan->status
                    ];
                }
                
                // 获取该计划的分配记录（小工单）
                $allocations = \app\admin\model\scanwork\Allocation::where('plan_id', $plan->id)
                    ->with(['process', 'user'])
                    ->select();
                
                foreach ($allocations as $allocation) {
                    $overallStats['total_allocations']++;
                    
                    // 按工序统计
                    if ($allocation->process) {
                        $processName = $allocation->process->name;
                        if (!isset($processStats[$processName])) {
                            $processStats[$processName] = [
                                'process_name' => $processName,
                                'total_allocations' => 0,
                                'total_quantity' => 0,
                                'completed_quantity' => 0,
                                'completion_rate' => 0,
                                'allocations' => []
                            ];
                        }
                        
                        $processStats[$processName]['total_allocations']++;
                        $processStats[$processName]['total_quantity'] += $allocation->quantity;
                        
                        // 获取报工记录
                        $reports = \app\admin\model\scanwork\Report::where('allocation_id', $allocation->id)
                            ->where('status', 1) // 已审核
                            ->sum('quantity');
                        
                        $completedQuantity = $reports ?: 0;
                        $processStats[$processName]['completed_quantity'] += $completedQuantity;
                        $overallStats['total_reports'] += $completedQuantity;
                        
                        $processStats[$processName]['allocations'][] = [
                            'allocation_id' => $allocation->id,
                            'plan_code' => $plan->plan_code,
                            'employee_name' => $allocation->user ? $allocation->user->nickname : '未知',
                            'allocated_quantity' => $allocation->quantity,
                            'completed_quantity' => $completedQuantity,
                            'completion_rate' => $allocation->quantity > 0 ? round(($completedQuantity / $allocation->quantity) * 100, 1) : 0,
                            'status' => $allocation->status
                        ];
                    }
                    
                    // 按员工统计
                    if ($allocation->user) {
                        $userId = $allocation->user->id;
                        $userName = $allocation->user->nickname;
                        
                        if (!isset($employeeStats[$userId])) {
                            $employeeStats[$userId] = [
                                'user_id' => $userId,
                                'user_name' => $userName,
                                'total_allocations' => 0,
                                'total_quantity' => 0,
                                'completed_quantity' => 0,
                                'completion_rate' => 0,
                                'allocations' => []
                            ];
                        }
                        
                        $employeeStats[$userId]['total_allocations']++;
                        $employeeStats[$userId]['total_quantity'] += $allocation->quantity;
                        
                        // 获取该员工的报工记录
                        $reports = \app\admin\model\scanwork\Report::where('allocation_id', $allocation->id)
                            ->where('status', 1)
                            ->sum('quantity');
                        
                        $completedQuantity = $reports ?: 0;
                        $employeeStats[$userId]['completed_quantity'] += $completedQuantity;
                        
                        $employeeStats[$userId]['allocations'][] = [
                            'allocation_id' => $allocation->id,
                            'plan_code' => $plan->plan_code,
                            'process_name' => $allocation->process ? $allocation->process->name : '未知',
                            'allocated_quantity' => $allocation->quantity,
                            'completed_quantity' => $completedQuantity,
                            'completion_rate' => $allocation->quantity > 0 ? round(($completedQuantity / $allocation->quantity) * 100, 1) : 0,
                            'status' => $allocation->status
                        ];
                    }
                    
                    // 按产品统计
                    if ($allocation->model && $allocation->model->product) {
                        $productId = $allocation->model->product->id;
                        $productName = $allocation->model->product->name;
                        $modelName = $allocation->model->name;
                        
                        if (!isset($productStats[$productId])) {
                            $productStats[$productId] = [
                                'product_id' => $productId,
                                'product_name' => $productName,
                                'total_plans' => 0,
                                'total_quantity' => 0,
                                'completed_quantity' => 0,
                                'completion_rate' => 0,
                                'models' => []
                            ];
                        }
                        
                        $productStats[$productId]['total_plans']++;
                        $productStats[$productId]['total_quantity'] += $plan->total_quantity;
                        
                        // 获取该产品的报工记录
                        $reports = \app\admin\model\scanwork\Report::where('allocation_id', $allocation->id)
                            ->where('status', 1)
                            ->sum('quantity');
                        
                        $completedQuantity = $reports ?: 0;
                        $productStats[$productId]['completed_quantity'] += $completedQuantity;
                        
                        // 按型号统计
                        if (!isset($productStats[$productId]['models'][$modelName])) {
                            $productStats[$productId]['models'][$modelName] = [
                                'model_name' => $modelName,
                                'total_quantity' => 0,
                                'completed_quantity' => 0,
                                'processes' => []
                            ];
                        }
                        
                        $productStats[$productId]['models'][$modelName]['total_quantity'] += $allocation->quantity;
                        $productStats[$productId]['models'][$modelName]['completed_quantity'] += $completedQuantity;
                        
                        // 按工序统计
                        $processName = $allocation->process ? $allocation->process->name : '未知';
                        if (!isset($productStats[$productId]['models'][$modelName]['processes'][$processName])) {
                            $productStats[$productId]['models'][$modelName]['processes'][$processName] = [
                                'process_name' => $processName,
                                'allocated_quantity' => 0,
                                'completed_quantity' => 0,
                                'completion_rate' => 0
                            ];
                        }
                        
                        $productStats[$productId]['models'][$modelName]['processes'][$processName]['allocated_quantity'] += $allocation->quantity;
                        $productStats[$productId]['models'][$modelName]['processes'][$processName]['completed_quantity'] += $completedQuantity;
                    }
                }
            }
            
            // 计算完成率
            foreach ($orderStats as &$order) {
                if ($order['total_quantity'] > 0) {
                    $order['completion_rate'] = round(($order['completed_quantity'] / $order['total_quantity']) * 100, 1);
                }
            }
            
            foreach ($processStats as &$process) {
                if ($process['total_quantity'] > 0) {
                    $process['completion_rate'] = round(($process['completed_quantity'] / $process['total_quantity']) * 100, 1);
                }
            }
            
            foreach ($employeeStats as &$employee) {
                if ($employee['total_quantity'] > 0) {
                    $employee['completion_rate'] = round(($employee['completed_quantity'] / $employee['total_quantity']) * 100, 1);
                }
            }
            
            foreach ($productStats as &$product) {
                if ($product['total_quantity'] > 0) {
                    $product['completion_rate'] = round(($product['completed_quantity'] / $product['total_quantity']) * 100, 1);
                }
                
                // 计算每个型号的完成率
                foreach ($product['models'] as &$model) {
                    if ($model['total_quantity'] > 0) {
                        $model['completion_rate'] = round(($model['completed_quantity'] / $model['total_quantity']) * 100, 1);
                    }
                    
                    // 计算每个工序的完成率
                    foreach ($model['processes'] as &$process) {
                        if ($process['allocated_quantity'] > 0) {
                            $process['completion_rate'] = round(($process['completed_quantity'] / $process['allocated_quantity']) * 100, 1);
                        }
                    }
                }
            }
            
            if ($overallStats['total_quantity'] > 0) {
                $overallStats['overall_completion_rate'] = round(($overallStats['completed_quantity'] / $overallStats['total_quantity']) * 100, 1);
            }
            
            // 获取筛选选项数据
            $orderList = \app\admin\model\scanwork\Order::column('order_name', 'id');
            $planList = $this->model->column('plan_name', 'id');
            $processList = \app\admin\model\scanwork\Process::column('name', 'id');
            $userList = \app\common\model\User::column('nickname', 'id');
            
            $this->view->assign([
                'orderStats' => $orderStats,
                'processStats' => $processStats,
                'employeeStats' => $employeeStats,
                'productStats' => $productStats,
                'overallStats' => $overallStats,
                'orderList' => $orderList,
                'planList' => $planList,
                'processList' => $processList,
                'userList' => $userList,
                'filters' => [
                    'order_id' => $orderId,
                    'plan_id' => $planId,
                    'process_id' => $processId,
                    'user_id' => $userId,
                    'date_range' => $dateRange
                ]
            ]);

            return $this->view->fetch();

        } catch (\Exception $e) {
            $this->error('获取生产进度失败：' . $e->getMessage());
        }
    }

    /**
     * 获取订单详情
     */
    public function getOrderDetails()
    {
        // 调试信息
        \think\Log::info("getOrderDetails方法被调用");
        
        $orderId = $this->request->get('order_id');
        \think\Log::info("订单ID: " . $orderId);
        
        if (!$orderId) {
            return json(['code' => 0, 'msg' => '订单ID不能为空']);
        }

        try {
            // 获取订单信息
            $order = \app\admin\model\scanwork\Order::find($orderId);
            if (!$order) {
                return json(['code' => 0, 'msg' => '订单不存在']);
            }

            // 获取该订单下的所有生产计划
            $plans = $this->model->where('order_id', $orderId)->select();
            
            $planDetails = [];
            foreach ($plans as $plan) {
                // 获取该计划的分配记录
                $allocations = \app\admin\model\scanwork\Allocation::where('order_id', $plan->order_id)
                    ->where('model_id', $plan->model_id)
                    ->with(['process', 'user'])
                    ->select();
                
                $allocationDetails = [];
                foreach ($allocations as $allocation) {
                    // 获取报工记录
                    $reports = \app\admin\model\scanwork\Report::where('allocation_id', $allocation->id)
                        ->where('status', 1)
                        ->sum('quantity');
                    
                    $allocationDetails[] = [
                        'allocation_id' => $allocation->id,
                        'process_name' => $allocation->process ? $allocation->process->name : '未知',
                        'employee_name' => $allocation->user ? $allocation->user->nickname : '未知',
                        'allocated_quantity' => $allocation->quantity,
                        'completed_quantity' => $reports ?: 0,
                        'completion_rate' => $allocation->quantity > 0 ? round(($reports / $allocation->quantity) * 100, 1) : 0,
                        'status' => $allocation->status_text
                    ];
                }
                
                $planDetails[] = [
                    'plan_id' => $plan->id,
                    'plan_code' => $plan->plan_code,
                    'plan_name' => $plan->plan_name,
                    'product_name' => $plan->product_name,
                    'product_model' => $plan->product_model,
                    'total_quantity' => $plan->total_quantity,
                    'allocations' => $allocationDetails
                ];
            }

            return json([
                'code' => 1,
                'msg' => '获取成功',
                'data' => [
                    'order' => $order,
                    'plans' => $planDetails
                ]
            ]);

        } catch (\Exception $e) {
            \think\Log::error("getOrderDetails异常: " . $e->getMessage());
            \think\Log::error("异常堆栈: " . $e->getTraceAsString());
            return json(['code' => 0, 'msg' => '获取订单详情失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取产品详情
     */
    public function getProductDetails()
    {
        \think\Log::info("getProductDetails方法被调用");
        
        $productId = $this->request->get('product_id');
        \think\Log::info("产品ID: " . $productId);
        
        if (!$productId) {
            return json(['code' => 0, 'msg' => '产品ID不能为空']);
        }

        try {
            // 获取产品信息
            $product = \app\admin\model\scanwork\Product::find($productId);
            if (!$product) {
                return json(['code' => 0, 'msg' => '产品不存在']);
            }

            // 获取该产品的所有型号
            $models = \app\admin\model\scanwork\ProductModel::where('product_id', $productId)->select();
            
            $modelDetails = [];
            foreach ($models as $model) {
                // 获取该型号的分配记录
                $allocations = \app\admin\model\scanwork\Allocation::where('model_id', $model->id)
                    ->with(['process', 'user'])
                    ->select();
                
                $processDetails = [];
                foreach ($allocations as $allocation) {
                    $processName = $allocation->process ? $allocation->process->name : '未知';
                    
                    if (!isset($processDetails[$processName])) {
                        $processDetails[$processName] = [
                            'process_name' => $processName,
                            'allocated_quantity' => 0,
                            'completed_quantity' => 0,
                            'completion_rate' => 0
                        ];
                    }
                    
                    $processDetails[$processName]['allocated_quantity'] += $allocation->quantity;
                    
                    // 获取报工记录
                    $reports = \app\admin\model\scanwork\Report::where('allocation_id', $allocation->id)
                        ->where('status', 1)
                        ->sum('quantity');
                    $processDetails[$processName]['completed_quantity'] += $reports ?: 0;
                }
                
                // 计算工序完成率
                foreach ($processDetails as &$process) {
                    if ($process['allocated_quantity'] > 0) {
                        $process['completion_rate'] = round(($process['completed_quantity'] / $process['allocated_quantity']) * 100, 1);
                    }
                }
                
                $modelDetails[] = [
                    'model_id' => $model->id,
                    'model_name' => $model->name,
                    'total_quantity' => array_sum(array_column($processDetails, 'allocated_quantity')),
                    'completed_quantity' => array_sum(array_column($processDetails, 'completed_quantity')),
                    'completion_rate' => 0, // 将在下面计算
                    'processes' => array_values($processDetails)
                ];
            }
            
            // 计算型号完成率
            foreach ($modelDetails as &$model) {
                if ($model['total_quantity'] > 0) {
                    $model['completion_rate'] = round(($model['completed_quantity'] / $model['total_quantity']) * 100, 1);
                }
            }

            return json([
                'code' => 1,
                'msg' => '获取成功',
                'data' => [
                    'product' => $product,
                    'models' => $modelDetails
                ]
            ]);

        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '获取产品详情失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取工序详情
     */
    public function getProcessDetails()
    {
        $processName = $this->request->get('process_name');
        if (!$processName) {
            return json(['code' => 0, 'msg' => '工序名称不能为空']);
        }

        try {
            // 获取工序信息
            $process = \app\admin\model\scanwork\Process::where('name', $processName)->find();
            if (!$process) {
                return json(['code' => 0, 'msg' => '工序不存在']);
            }

            // 获取该工序的所有分配记录
            $allocations = \app\admin\model\scanwork\Allocation::where('process_id', $process->id)
                ->with(['user', 'order', 'model.product'])
                ->select();
            
            $allocationDetails = [];
            foreach ($allocations as $allocation) {
                // 获取报工记录
                $reports = \app\admin\model\scanwork\Report::where('allocation_id', $allocation->id)
                    ->where('status', 1)
                    ->sum('quantity');
                
                $allocationDetails[] = [
                    'allocation_id' => $allocation->id,
                    'order_name' => $allocation->order ? $allocation->order->order_name : '未知',
                    'product_name' => $allocation->model && $allocation->model->product ? $allocation->model->product->name : '未知',
                    'model_name' => $allocation->model ? $allocation->model->name : '未知',
                    'employee_name' => $allocation->user ? $allocation->user->nickname : '未知',
                    'allocated_quantity' => $allocation->quantity,
                    'completed_quantity' => $reports ?: 0,
                    'completion_rate' => $allocation->quantity > 0 ? round(($reports / $allocation->quantity) * 100, 1) : 0,
                    'status' => $allocation->status_text
                ];
            }

            return json([
                'code' => 1,
                'msg' => '获取成功',
                'data' => [
                    'process' => $process,
                    'allocations' => $allocationDetails
                ]
            ]);

        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '获取工序详情失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取员工详情
     */
    public function getEmployeeDetails()
    {
        $userId = $this->request->get('user_id');
        if (!$userId) {
            return json(['code' => 0, 'msg' => '员工ID不能为空']);
        }

        try {
            // 获取员工信息
            $user = \app\common\model\User::find($userId);
            if (!$user) {
                return json(['code' => 0, 'msg' => '员工不存在']);
            }

            // 获取该员工的所有分配记录
            $allocations = \app\admin\model\scanwork\Allocation::where('user_id', $userId)
                ->with(['process', 'order', 'model.product'])
                ->select();
            
            $allocationDetails = [];
            foreach ($allocations as $allocation) {
                // 获取报工记录
                $reports = \app\admin\model\scanwork\Report::where('allocation_id', $allocation->id)
                    ->where('status', 1)
                    ->sum('quantity');
                
                $allocationDetails[] = [
                    'allocation_id' => $allocation->id,
                    'order_name' => $allocation->order ? $allocation->order->order_name : '未知',
                    'product_name' => $allocation->model && $allocation->model->product ? $allocation->model->product->name : '未知',
                    'model_name' => $allocation->model ? $allocation->model->name : '未知',
                    'process_name' => $allocation->process ? $allocation->process->name : '未知',
                    'allocated_quantity' => $allocation->quantity,
                    'completed_quantity' => $reports ?: 0,
                    'completion_rate' => $allocation->quantity > 0 ? round(($reports / $allocation->quantity) * 100, 1) : 0,
                    'status' => $allocation->status_text
                ];
            }

            return json([
                'code' => 1,
                'msg' => '获取成功',
                'data' => [
                'user' => $user,
                'allocations' => $allocationDetails]
            ]);

        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '获取员工详情失败：' . $e->getMessage()]);
        }
    }

    /**
     * 为分配任务生成报工二维码
     */
    private function generateQrcodeForAllocation($allocationId)
    {
        // 检查是否已有二维码
        $existingQrcode = \app\admin\model\scanwork\Qrcode::where('allocation_id', $allocationId)->find();
        if ($existingQrcode) {
            \think\Log::info('分配ID ' . $allocationId . ' 已存在二维码，跳过生成');
            return;
        }

        // 获取分配信息
        $allocation = \app\admin\model\scanwork\Allocation::with(['order', 'model.product', 'process', 'user'])->find($allocationId);
        if (!$allocation) {
            throw new \Exception('分配任务不存在');
        }

        // 生成二维码内容（URL格式）
        $baseUrl = $this->request->domain();
        $qrContent = $baseUrl . '/index/worker/scan?allocation_id=' . $allocationId;

        // 生成二维码图片
        $qrImage = $this->generateQrImage($qrContent, $allocation);

        // 保存二维码记录
        \app\admin\model\scanwork\Qrcode::create([
            'allocation_id' => $allocationId,
            'qr_content' => $qrContent,
            'qr_image' => $qrImage,
            'scan_count' => 0,
            'status' => 0,
            'createtime' => time()
        ]);
    }

    /**
     * 生成二维码图片
     */
    private function generateQrImage($content, $allocation)
    {
        try {
            // 使用二维码生成库
            $qrCode = new \Endroid\QrCode\QrCode($content);
            $qrCode->setSize(300);
            $qrCode->setMargin(10);
            
            // 设置二维码颜色 - 使用Color对象
            $qrCode->setForegroundColor(new \Endroid\QrCode\Color\Color(0, 0, 0));
            $qrCode->setBackgroundColor(new \Endroid\QrCode\Color\Color(255, 255, 255));
            
            // 生成文件名
            $filename = 'allocation_' . $allocation->id . '_' . time() . '.png';
            $uploadPath = '/uploads/qrcode/' . date('Ymd') . '/';
            $fullPath = ROOT_PATH . 'public' . $uploadPath;
            
            // 创建目录
            if (!is_dir($fullPath)) {
                mkdir($fullPath, 0755, true);
            }
            
            // 使用Writer来保存图片
            $writer = new \Endroid\QrCode\Writer\PngWriter();
            $result = $writer->write($qrCode);
            $result->saveToFile($fullPath . $filename);
            
            return $uploadPath . $filename;
        } catch (\Exception $e) {
            \think\Log::error('二维码图片生成失败：' . $e->getMessage());
            throw $e;
        }
    }

    /**
     * 智能排程建议
     */
    public function getScheduleSuggestions()
    {
        if ($this->request->isAjax()) {
            $planId = $this->request->param('plan_id');
            if (empty($planId)) {
                $this->error('请选择生产计划');
            }
            
            // 获取生产计划详情
            $plan = $this->model->get($planId);
            if (!$plan) {
                $this->error('生产计划不存在');
            }
            
            // 分析当前计划并提供优化建议
            $suggestions = $this->analyzeProductionPlan($plan);
            
            $this->success('获取成功', '', $suggestions);
        }
    }

    /**
     * 分析生产计划并提供建议
     */
    private function analyzeProductionPlan($plan)
    {
        $suggestions = [];
        
        // 分析资源利用率
        $resourceUtilization = $this->calculateResourceUtilization($plan);
        if ($resourceUtilization['low_utilization'] > 0) {
            $suggestions[] = [
                'type' => 'warning',
                'title' => '资源利用率偏低',
                'message' => "有{$resourceUtilization['low_utilization']}个资源利用率低于70%，建议重新分配任务"
            ];
        }
        
        // 分析时间安排
        $timeAnalysis = $this->analyzeTimeArrangement($plan);
        if ($timeAnalysis['conflicts'] > 0) {
            $suggestions[] = [
                'type' => 'error',
                'title' => '时间安排冲突',
                'message' => "发现{$timeAnalysis['conflicts']}个时间冲突，需要调整"
            ];
        }
        
        // 分析优先级
        $priorityAnalysis = $this->analyzePriority($plan);
        if (!empty($priorityAnalysis['issues'])) {
            $suggestions[] = [
                'type' => 'info',
                'title' => '优先级建议',
                'message' => "建议调整" . count($priorityAnalysis['issues']) . "个任务的优先级"
            ];
        }
        
        return $suggestions;
    }

    /**
     * 计算资源利用率
     */
    private function calculateResourceUtilization($plan)
    {
        // 获取计划相关的分配记录
        $allocations = Db::name('scanwork_allocation')
            ->where('plan_id', $plan['id'])
            ->select();
        
        $resourceStats = [];
        $lowUtilization = 0;
        
        foreach ($allocations as $allocation) {
            $resourceId = $allocation['resource_id'];
            $resourceType = $allocation['resource_type'];
            
            if (!isset($resourceStats[$resourceType])) {
                $resourceStats[$resourceType] = [];
            }
            
            if (!isset($resourceStats[$resourceType][$resourceId])) {
                $resourceStats[$resourceType][$resourceId] = [
                    'total_capacity' => 8, // 假设8小时工作制
                    'used_capacity' => 0
                ];
            }
            
            $resourceStats[$resourceType][$resourceId]['used_capacity'] += $allocation['planned_hours'] ?? 0;
        }
        
        foreach ($resourceStats as $type => $resources) {
            foreach ($resources as $resourceId => $stats) {
                $utilization = $stats['used_capacity'] / $stats['total_capacity'];
                if ($utilization < 0.7) {
                    $lowUtilization++;
                }
            }
        }
        
        return [
            'low_utilization' => $lowUtilization,
            'stats' => $resourceStats
        ];
    }

    /**
     * 分析时间安排
     */
    private function analyzeTimeArrangement($plan)
    {
        $conflicts = 0;
        
        // 获取计划的时间安排
        $allocations = Db::name('scanwork_allocation')
            ->where('plan_id', $plan['id'])
            ->where('start_time', '>', 0)
            ->where('end_time', '>', 0)
            ->select();
        
        // 按资源分组检查时间冲突
        $resourceAllocations = [];
        foreach ($allocations as $allocation) {
            $resourceKey = $allocation['resource_type'] . '_' . $allocation['resource_id'];
            if (!isset($resourceAllocations[$resourceKey])) {
                $resourceAllocations[$resourceKey] = [];
            }
            $resourceAllocations[$resourceKey][] = $allocation;
        }
        
        foreach ($resourceAllocations as $resourceKey => $allocations) {
            for ($i = 0; $i < count($allocations); $i++) {
                for ($j = $i + 1; $j < count($allocations); $j++) {
                    if ($this->isTimeConflict($allocations[$i], $allocations[$j])) {
                        $conflicts++;
                    }
                }
            }
        }
        
        return ['conflicts' => $conflicts];
    }

    /**
     * 检查时间冲突
     */
    private function isTimeConflict($allocation1, $allocation2)
    {
        $start1 = $allocation1['start_time'];
        $end1 = $allocation1['end_time'];
        $start2 = $allocation2['start_time'];
        $end2 = $allocation2['end_time'];
        
        return !($end1 <= $start2 || $end2 <= $start1);
    }

    /**
     * 分析优先级
     */
    private function analyzePriority($plan)
    {
        $issues = [];
        
        // 获取计划相关的订单
        $orders = Db::name('scanwork_order')
            ->where('plan_id', $plan['id'])
            ->order('priority', 'desc')
            ->order('delivery_date', 'asc')
            ->select();
        
        $urgentOrders = [];
        $normalOrders = [];
        
        foreach ($orders as $order) {
            if ($order['priority'] == 'high' || $order['priority'] == 'urgent') {
                $urgentOrders[] = $order;
            } else {
                $normalOrders[] = $order;
            }
        }
        
        // 检查紧急订单是否排在前面
        foreach ($urgentOrders as $urgentOrder) {
            foreach ($normalOrders as $normalOrder) {
                if ($normalOrder['start_date'] < $urgentOrder['start_date']) {
                    $issues[] = [
                        'order_id' => $urgentOrder['id'],
                        'issue' => '紧急订单前有普通订单'
                    ];
                    break;
                }
            }
        }
        
        return ['issues' => $issues];
    }

    /**
     * 获取排程优化建议
     */
    public function getOptimizationSuggestions()
    {
        if ($this->request->isAjax()) {
            $planId = $this->request->param('plan_id');
            if (empty($planId)) {
                $this->error('请选择生产计划');
            }
            
            // 调用排程引擎获取优化建议
            $scheduleEngine = new \app\admin\library\ScheduleEngine();
            $suggestions = $scheduleEngine->getOptimizationSuggestions($planId);
            
            $this->success('获取成功', '', $suggestions);
        }
    }
}
